package com.example.mq.service;

import com.alibaba.fastjson.JSON;
import com.example.mq.config.MsgBinding;
import com.example.mq.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

/**
 * Kafka生产者
 * Created by liulanhua on 2018/9/4.
 */
@Slf4j
@Component
@EnableBinding(MsgBinding.class)
public class MsgSender {

    @Autowired
    private MsgBinding source;

    /**
     * 发送消息方法
     * @param msg
     */
    public void send(String msg) {
        log.info("KafkaSender发送消息,消息内容 : {}", msg);
        try {
            String uuid = UUID.randomUUID().toString();
            Message message = new Message();
            message.setId(uuid);
            message.setMsg(msg);
            message.setSendTime(new Date());

            source.sendMsg().send(MessageBuilder.withPayload(JSON.toJSONString(message)).build());

        }catch (Exception e){
            log.error("KafkaSender发送消息异常",e);
        }
    }



}
